<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @on-load="onLoad">
      <template slot="categoryIcon" slot-scope="scope"  v-if="scope.row.categoryIcon!=''">
        <el-image
          style="width: 100px; height: 100px"
          :src="scope.row.categoryIcon"
          :fit="fit">
        </el-image>
      </template>
      <template slot="status" slot-scope="scope" >
        <avue-switch v-model="scope.row.status" @click="rowUpdate(scope.row)" :dic="[{value:0},{value:1}]"></avue-switch>
      </template>
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.category_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-button size="small"
                   icon="el-icon-s-tools"
                   @click="handleAttr"
                   plain>属性配置
        </el-button>
      </template>
    </avue-crud>
    <el-dialog title="分类属性配置"
               :visible.sync="box"
               width="800px">
      <el-tabs type="border-card" @tab-click="handleTab">
        <el-tab-pane label="关联属性" >
          <avue-crud :data="attrData"
                     :option="attrOption"
                     @current-change="attrCurrentChange"
                     @on-load="attrLoad"
                     :table-loading="attrLoading"
                     ref="attrCrud"
                     @search-change="attrSearchChange"
                     @search-reset="attrSearchReset"
                     @selection-change="attrSelectionChange"
                     :page="attrPage"
                     @size-change="attrSizeChange">
            <template slot-scope="scope" slot="menu" >
              <el-button icon="el-icon-plus" type="text" size="small" @click="handleRemoveAttr(scope.row.relationId)">删除属性</el-button>
            </template>
          </avue-crud>
        </el-tab-pane>
        <el-tab-pane label="其他属性" >

          <avue-crud :data="attrAllData"
                     :option="attrOption"
                     @current-change="attrAllCurrentChange"
                     @on-load="attrAllLoad"
                     :table-loading="attrLoading"
                     ref="attrCrud"
                     @search-change="attrAllSearchChange"
                     @search-reset="attrAllSearchReset"
                     @selection-change="attrAllSelectionChange"
                     :page="attrAllPage"
                     @size-change="attrAllSizeChange">
            <template slot="attrName" slot-scope="scope" >
              <el-tag v-if="scope.row.relationId===-1" type="danger">{{scope.row.attrName}} 未使用</el-tag>
              <el-tag v-else >{{scope.row.attrName}}</el-tag>
            </template>
            <template slot-scope="scope" slot="menu" >
              <el-button icon="el-icon-plus" type="text" size="small" @click="handleAddAttr(scope.row.id)">添加属性</el-button>
            </template>
            <template slot="menuLeft">
              <el-tag>从未被使用的属性将始终优先展示</el-tag>
            </template>
          </avue-crud>

        </el-tab-pane>
      </el-tabs>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="box = false">取 消</el-button>
        <el-button type="primary"
                   @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
  import {add, getDetail, getList, remove, update , getAttr, getAttrByCategory , addAttr , removeAttr} from "@/api/category/category";
  import {mapGetters} from "vuex";

  export default {
    data() {
      return {
        form: {},
        query: {},
        attrQuery: {},
        attrAllQuery: {},
        loading: true,
        attrLoading:true,
        attrAllLoading:true,
        box:false,
        attrAllPage: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        attrPage: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        attrSelectionList: [],
        attrOption: {    excelBtn:true,
          menu:true,
          menuWidth: 150,
          viewBtn: false,
          editBtn: false,
          addBtn: false,
          delBtn: false,
          searchShow: true,
          tip: false,
          tree: true,
          border: true,
          index: true,
          selection: true,
          column: [
            {
              label: "属性名",
              prop: "attrName",
              search: true,
              searchSpan:16,
              rules: [{
                required: false,
                message: "请输入",
                trigger: "blur"
              }]
            },{
              label: "属性级别",
              prop: "attrRank",
              type:"tree",
              dicData: [{'title':'普通属性',value:1},{'title':'支持搜索',value: 2}],
              props: {
                label: "title",
                value: "value"
              }
            }
          ]
        },
        attrData: [],
        attrAllData: [],
        option: {    excelBtn:true,
          height: 'auto',
          calcHeight: 210,
          searchShow: true,
          searchMenuSpan: 6,
          tip: false,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          column: [
            {
              label: "上级菜单",
              prop: "parentId",
              hide: true,
              type: "tree",
              dicUrl: "/api/ocm-product/category/list",
              props: {
                label: "categoryName",
                value: "id"
              },
              rules: [{
                required: false,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "分类名",
              prop: "categoryName",
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "分类图标",
              prop: "categoryIcon",
              type: "upload",
              listType: 'picture-img',
              propsHttp: {
                res: 'data',
                url: 'link',
              },
              canvasOption: {    excelBtn:true,
                text: 'ocm',
              },
              action: '/api/ocm-resource/oss/endpoint/put-file',
              tip: '只能上传jpg/png用户头像，且不超过500kb',
              span: 12,
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "分类级别",
              prop: "categoryRank",
              hide:true,
              rules: [{
                required: false,
                message: "请输入",
                trigger: "blur"
              }]
            },{
              label: "排序",
              prop: "sort",
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "状态",
              prop: "status",
              type: 'switch',
              editDisplay: false,
              dicData: [{
                value:'0'
              },{
                value:'1'
              }],
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },

          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.category_add, false),
          viewBtn: this.vaildData(this.permission.category_view, false),
          delBtn: this.vaildData(this.permission.category_delete, false),
          editBtn: this.vaildData(this.permission.category_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      handleTab(t){
        if(t.index==='0') this.attrLoad(this.attrPage)
        if(t.index==='1') this.attrAllLoad(this.attrAllPage)
      },
      handleAddAttr(id){
        addAttr({
          'attrIds':id,
          'categoryId':this.selectionList[0].id
        }).then(res=>{
          this.attrAllLoad(this.attrAllPage)
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        })
      },
      handleRemoveAttr(id){
        removeAttr(
         id
        ).then(res=>{
          this.attrLoad(this.attrPage)
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        })
      },
      attrLoad(attrPage){
        getAttrByCategory(attrPage.currentPage, attrPage.pageSize, Object.assign( this.attrQuery,{'r.categoryId_equal':this.selectionList[0].id})).then(res => {
          this.attrLoading=true;
          const data = res.data.data;
          this.attrData = data.records;
          this.attrLoading = false;
          this.attrPage.total = data.total;
          this.attrSelectionClear();
        });
      },
      attrAllLoad(attrAllPage){
        getAttrByCategory(attrAllPage.currentPage, attrAllPage.pageSize,
          Object.assign(this.attrAllQuery,
            {'categoryId':this.selectionList[0].id})
        ).then(res => {
          this.attrAllLoading=true;
          const data = res.data.data;
          this.attrAllData = data.records;
          this.attrAllLoading = false;
          this.attrAllPage.total = data.total;
          this.attrSelectionClear();
        });
      },
      handleAttr(){
        if (this.selectionList.length !== 1||this.selectionList[0].parentId==='0') {
          this.$message.warning("只能选择一条二级分类数据");
          return;
        }
        this.attrLoad(this.attrPage)
        this.attrAllLoad(this.attrAllPage)
        this.box=true;
      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          done();
          this.onLoad();
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          done();
          this.onLoad();
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad();
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad();
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      attrSearchReset() {
        this.attrQuery = {};
        this.attrLoad(this.page);
      },
      attrSearchChange(params, done) {
        this.attrQuery = params;
        this.attrPage.currentPage = 1;
        this.attrLoad(this.attrPage, params);
        done();
      },
      attrSelectionChange(list) {
        this.attrSelectionList = list;
      },
      attrAllSearchReset() {
        this.attrQuery = {};
        this.attrLoad(this.page);
      },
      attrAllSearchChange(params, done) {
        this.attrAllQuery = params;
        this.attrAllPage.currentPage = 1;
        this.attrAllLoad(this.attrAllPage, params);
        done();
      },
      attrAllSelectionChange(list) {
        this.attrAllSelectionList = list;
      },
      attrSelectionClear() {
        this.attrSelectionList = [];
        this.$refs.attrCrud.toggleSelection();
      },
      searchReset() {
        this.query = {};
        this.onLoad();
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.$refs.crud.toggleSelection();
      },
      attrAllCurrentChange(currentPage){
        this.attrAllPage.currentPage = currentPage;
      },
      attrCurrentChange(currentPage){
        this.attrPage.currentPage = currentPage;
      },
      attrSizeChange(pageSize){
        this.attrPage.pageSize = pageSize;
      },
      attrAllSizeChange(pageSize){
        this.attrAllPage.pageSize = pageSize;
      },
      onLoad( params = {}) {
        this.loading = true;
        getList(Object.assign(params, this.query)).then(res => {
          this.data = res.data.data;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
